import requests
import traceback
import json

from flask import current_app as app

from app.db import redis
from app.errors import SEEBUGAPIException, SEEBUGAPINotOk


class SeeBug(object):
    def __init__(self):
        self._base_url = app.config['SEEBUG']['url']
        self._headers = {'Authorization': f"Token {app.config['SEEBUG']['token']}"}

    def _ajax(self, method, url, data):
        new_url = f"{self._base_url}{url}"
        request_args = {'url': new_url, 'headers': self._headers}
        if method == 'GET':
            request_func = requests.get
            request_args['params'] = data
        else:
            request_func = requests.post
            request_args['data'] = data

        try:
            app.logger.info(f"""Begin request. url: {new_url} params: {str(data)[:150]} method:{method}""")
            resp = request_func(**request_args)
            text = resp.text[:150]
            app.logger.info(f"""END request. code: {resp.status_code} resp: {text}""")

            if resp.status_code != 200:
                raise SEEBUGAPIException(msg=text)

            redis.set(f"seebug_cache_{url}", resp.text)
            return json.loads(resp.text)
        except Exception as e:
            app.logger.info(e)
            traceback.print_exc()
            raise SEEBUGAPINotOk()

    def get(self, url, params=''):
        return self._ajax('GET', url, params)

    def post(self, url, data):
        return self._ajax('POST', url, data)
